package com.abe.libquick.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.Button;

@SuppressLint({"ClickableViewAccessibility", "AppCompatCustomView"})
public class LongTouchBtn extends Button {

    private boolean clickDown = false;
    private LongTouchListener mListener;
    //按钮长按时 间隔多少毫秒来处理 回调方法
    private int mTime;
    //按下时间
    private long startTime;

    public LongTouchBtn(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            startTime = System.currentTimeMillis();
            clickDown = true;
            /* 长按判断逻辑 */
            new Thread(new LongTouchThread()).start();
            if (mListener != null) {
                mListener.onStartTouch();
            }
        } else if (event.getAction() == MotionEvent.ACTION_UP) {
            //弹起时间
            long endTime = System.currentTimeMillis();
            long diff = endTime - startTime;// 这样得到的差值是微秒级别时间差
            if ((diff - mTime) > 0) {
                if (mListener != null) {
                    mListener.onEndTouch();
                }
            }
            clickDown = false;
        }
        return super.onTouchEvent(event);
    }

    /**
     * 给长按btn控件注册一个监听器。
     *
     * @param listener 监听器的实现。
     * @param time     多少毫秒时间间隔 来处理一次回调方法
     */
    public void setOnLongTouchListener(LongTouchListener listener, int time) {
        mListener = listener;
        mTime = time;
    }

    //长按监听接口
    public interface LongTouchListener {
        //开始
        void onStartTouch();

        //处理长按的回调方法
        void onLongTouch();

        //长按结束
        void onEndTouch();
    }

    class LongTouchThread implements Runnable {

        @Override
        public void run() {
            int count = 0;
            /* 当手指未弹起且未达到限制时长 */
            while (clickDown && count * 100 < mTime) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                count++;
            }
            /* 长按未结束 */
            if (clickDown) {
                new MyHandler(Looper.getMainLooper()).sendEmptyMessage(0x001);
            }
        }
    }

    class MyHandler extends Handler {
        MyHandler(Looper looper) {
            super(looper);
        }

        public void handleMessage(Message msg) {
            mListener.onLongTouch();
        }
    }
}